package com.UnionPayCenter.distribution.manager.impl;

import com.UnionPayCenter.distribution.domain.DistributionUser;
import com.UnionPayCenter.distribution.dto.PageQueryBaseDTO;
import com.UnionPayCenter.distribution.entity.UserDistributionDO;
import com.UnionPayCenter.distribution.entity.UserDistributionRefDO;
import com.UnionPayCenter.distribution.manager.UserDistributionRefManager;
import com.UnionPayCenter.mapper.UserDistributionRefDOMapper;
import com.UnionPayCenter.service.IUserService;
import com.UnionPayCenter.service.ServiceTemplate;
import com.github.pagehelper.Page;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Noah
 * @since 1.0.0, 2019/07/03
 */
@Service
public class UserDistributionRefManagerImpl implements UserDistributionRefManager {

    @Autowired
    private UserDistributionRefDOMapper userDistributionRefDOMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private ServiceTemplate serviceTemplate;

    /**
     * 初始化分销用户信息关系表
     *
     * @param user               请求信息
     * @param userDistributionDO 用户分销信息
     */
    @Override
    public void initUserDistributionRef(DistributionUser user, UserDistributionDO userDistributionDO) {
        if (Objects.isNull(user) || Objects.isNull(userDistributionDO) || Objects.isNull(user.getCounterpartyUserVo())) {
            return;
        }
        UserDistributionRefDO exists = userDistributionRefDOMapper.selectByCounterpartyUserId(user.getBId(),
                user.getShopId(), null, user.getCounterpartyUserVo().getUserId().longValue());
        if (Objects.nonNull(exists)) {
            if (Objects.isNull(exists.getUserId()) && Objects.nonNull(user.getUserVo())) {
                exists.setUserId(user.getUserVo().getUserId().longValue());
                exists.setUserName(user.getUserVo().getNick());
                exists.setUserMobile(user.getUserVo().getMobile());
                userDistributionRefDOMapper.updateByPrimaryKeySelective(exists);
            }
            return;
        }
        Date date = new Date();
        UserDistributionRefDO refDO = new UserDistributionRefDO();
        refDO.setInfoSn(userDistributionDO.getInfoSn());
        refDO.setTIdgen(Integer.valueOf(userDistributionDO.getIdgen()));
        if (Objects.nonNull(user.getUserVo())) {
            refDO.setUserId(user.getUserVo().getUserId().longValue());
            refDO.setUserName(user.getUserVo().getNick());
            refDO.setUserMobile(user.getUserVo().getMobile());
        }
        refDO.setBId(user.getBId());
        refDO.setShopId(user.getShopId());
        refDO.setCounterpartyUserId(user.getCounterpartyUserVo().getUserId().longValue());
        refDO.setCounterpartyUserName(user.getCounterpartyUserVo().getNick());
        refDO.setCounterpartyUserMobile(user.getCounterpartyUserVo().getMobile());
        refDO.setShareValTime(new Date(2114352000000L));
        refDO.setShareLvl(1);
        refDO.setDisType(null);
        refDO.setCreateTime(date);
        refDO.setUpdateTime(date);
        refDO.setRemark(null);
        userDistributionRefDOMapper.insertSelective(refDO);
    }

    /**
     * 根据分销对手ID获取用户信息
     *
     * @param bId
     * @param shopId
     * @param counterpartyUserId
     * @return
     */
    @Override
    public UserDistributionRefDO selectByCounterpartyUser(Long bId, Long shopId, Long counterpartyUserId) {
        return userDistributionRefDOMapper.selectByCounterpartyUserId(bId, shopId, null, counterpartyUserId);
    }

    /**
     * @param bId    商铺ID
     * @param shopId 店铺ID
     * @param userId 用户ID
     * @return
     */
    @Override
    public int countRecordFilterBlankMobileByUserId(Long bId, Long shopId, Long userId, Integer level) {
        PageQueryBaseDTO pageQueryBaseDTO = new PageQueryBaseDTO();
        pageQueryBaseDTO.setPageSize(1);
        pageQueryBaseDTO.setPage(1);
        Page<UserDistributionRefDO> page;
        if (1 == level) {
            page=pageFirstRecordFilterBlankMobileByUserId( bId,  shopId,  userId,pageQueryBaseDTO);
        } else if (2 == level) {
            page= pageSecondRecordFilterBlankMobileByUserId( bId,  shopId,  userId,pageQueryBaseDTO);
        } else {
            page= pageAllRecordFilterBlankMobileByUserId( bId,  shopId,  userId,pageQueryBaseDTO);
        }
        return Objects.nonNull(page) ?  new Long(page.getTotal()).intValue() : 0;
    }

    /**
     * 根据分销员ID获取用户信息
     *
     * @param bId    商铺id
     * @param shopId 店铺ID
     * @param userId 对手ID
     * @return
     */
    @Override
    public List<UserDistributionRefDO> listByUserId(Long bId, Long shopId, Long userId) {
        return userDistributionRefDOMapper.listRecordByUserId(bId, shopId, userId);
    }


    @Override
    public Page<UserDistributionRefDO> pageSecondRecordFilterBlankMobileByUserId(Long bId, Long shopId, Long userId, PageQueryBaseDTO pageQueryBaseDTO) {
        return serviceTemplate.pagination(pageQueryBaseDTO.getPage(), pageQueryBaseDTO.getPageSize(),
                () -> userDistributionRefDOMapper.listSecondRecordFilterBlankMobileByUserId(bId, shopId, userId));
    }

    /**
     * 根据分销员ID获取用户信息
     *
     * @param bId              商铺id
     * @param shopId           店铺ID
     * @param userId           对手ID
     * @param pageQueryBaseDTO
     * @return
     */
    @Override
    public Page<UserDistributionRefDO> pageFirstRecordFilterBlankMobileByUserId(Long bId, Long shopId, Long userId, PageQueryBaseDTO pageQueryBaseDTO) {
        return serviceTemplate.pagination(pageQueryBaseDTO.getPage(), pageQueryBaseDTO.getPageSize(),
                () -> userDistributionRefDOMapper.listFirstRecordFilterBlankMobileByUserId(bId, shopId, userId));
    }

    @Override
    public Page<UserDistributionRefDO> pageAllRecordFilterBlankMobileByUserId(Long bId, Long shopId, Long userId, PageQueryBaseDTO pageQueryBaseDTO) {
        return serviceTemplate.pagination(pageQueryBaseDTO.getPage(), pageQueryBaseDTO.getPageSize(),
                () -> userDistributionRefDOMapper.listAllRecordFilterBlankMobileByUserId(bId, shopId, userId));
    }

    //    /**
//     * 根据userid获取下级用户信息
//     *
//     * @param bId    商铺ID
//     * @param shopId 店铺ID
//     * @param userId 用户ID
//     * @return
//     */
//    @Override
//    public List<DistributionUserRefVO> listSubUserByUserId(Long bId, Long shopId, Long userId) {
//        List<UserDistributionRefDO> refDOList = userDistributionRefDOMapper.listRecordByUserId(bId, shopId, userId);
//        if(CollectionUtils.isEmpty(refDOList)){
//            return Collections.emptyList();
//        }
//        return refDOList.stream().map(e->{
//            DistributionUserRefVO refVO = new DistributionUserRefVO();
//            refVO.
//
//        }).collect(Collectors.toList());
//    }

    /**
     * 根据userId获取所有记录条数
     *
     * @param bId    商铺ID
     * @param shopId 店铺ID
     * @param userId 用户ID
     * @param level  层级
     * @return
     */
    @Override
    public int countAllRecordByUserId(Long bId, Long shopId, Long userId, Integer level) {
        return countAllRecordByUserId(bId, shopId, userId, level, 1);
    }

    private int countAllRecordByUserId(Long bId, Long shopId, Long userId, Integer totalLevel, Integer currentLevel) {
        if (Objects.isNull(totalLevel) || Objects.isNull(currentLevel) || totalLevel.compareTo(currentLevel) < 0) {
            return 0;
        }
        List<UserDistributionRefDO> refDoList = userDistributionRefDOMapper.listRecordByUserId(bId, shopId, userId);
        if (CollectionUtils.isEmpty(refDoList)) {
            return 0;
        }
        int count = refDoList.size();
        currentLevel = currentLevel + 1;
        for (UserDistributionRefDO refDO : refDoList) {
            int size = countAllRecordByUserId(bId, shopId, refDO.getCounterpartyUserId(), totalLevel, currentLevel);
            count = count + size;
        }
        return count;
    }

    /**
     * 分页获取用户信息
     *
     * @param userDo   条件信息
     * @param page
     * @param pageSize
     * @return 分销流水列表
     */
    @Override
    public Page<UserDistributionRefDO> pageDistributionSn(UserDistributionRefDO userDo, Integer page, Integer pageSize) {
        return serviceTemplate.pagination(page, pageSize, () -> userDistributionRefDOMapper.listUserDistributionRefDOWithSuper(userDo));
    }
}
